//
//  LBStatisticsTask.m
//  LBStatistics
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBStatisticsTask.h"
#import <AFNetworking/AFNetworking.h>
#import <LBFoundation/LBFoundation.h>
#import "LBStatisticsMacros.h"

//重新发送的时间间隔
#define retryTimeInterval 5
//默认的最大任务重试次数
#define kDefaultMaxRetryCount 5

@interface LBStatisticsTask ()

@property (nonatomic, strong,readwrite) NSArray *taskDatas;

/** 服务器地址 */
@property (nonatomic, copy,readwrite) NSString *url;
/** 重试参数 */
@property (nonatomic, copy,readwrite) NSString *params;

//任务中所有数据，都属于相同的type类型
@property (nonatomic, assign,readwrite) LBStatisticsTaskType type;

/** 请求所出的状态 */
@property (nonatomic, assign,readwrite) LBStatisticsTaskState state;

/** 重试次数 */
@property (nonatomic, assign,readwrite) NSInteger retryCount;

@property (nonatomic, strong) NSURLSessionTask *sessionTask;

@end

@implementation LBStatisticsTask

- (void)dealloc{
//    for (StatisticsTaskData *taskData in self.taskDatas)
//    {
//        LBSLog(@"StatisticsTask Dealloc %@, %@",taskData.url,taskData.params);
//    }
}

- (instancetype)initWithTaskDatas:(NSArray *)taskDatas{
    if (self = [super init]) {
        self.taskDatas = taskDatas;
        self.maxRetryCount = kDefaultMaxRetryCount;
        self.state = LBStatisticsTaskStateWaiting;
        
        LBStatisticsTaskData *firstTaskData = [self.taskDatas firstObject];
        self.url = firstTaskData.url;
        self.type = firstTaskData.type;
        
        if (self.type == LBStatisticsTaskTypeAd)
        {
            NSMutableDictionary *paramDict = [[firstTaskData.params yy_stringToJSONObject] mutableCopy];
            NSMutableArray *actions = [NSMutableArray array];
            for (LBStatisticsTaskData *taskData in taskDatas){
                if (taskData.action.length > 0) {
                    [actions addObject:taskData.action];
                }
            }
            
            [paramDict setObject:actions forKey:@"action"];
            self.params = [paramDict yy_modelToJSONString];
        }
        else{
            self.params = firstTaskData.params;
        }
        
    }
    return self;
}


/** 开始发送 */
- (void)start{
    [self send];
}


/** 停止发送 */
- (void)stop{
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    self.state = LBStatisticsTaskStateWaiting;
//    [self.httpRequest clearDelegatesAndCancel];
    [self.sessionTask cancel];
}

/** 重新发送 */
- (void)retryDo{
    if (self.retryCount < self.maxRetryCount) {
        self.state = LBStatisticsTaskStateReSendWaiting;
        [self performSelector:@selector(resend) withObject:nil afterDelay:retryTimeInterval];
    }
    else{
        self.state = LBStatisticsTaskStateFail;
        [self increaseFailCount];
        if ([self.delegate respondsToSelector:@selector(taskFail:)]) {
            [self.delegate taskFail:self];
        }
    }
}

//增加失败次数
- (void)increaseFailCount{
    for (LBStatisticsTaskData *taskData in self.taskDatas)
    {
        taskData.failCount ++;
    }
}

- (void)send{
  
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self.sessionTask cancel];
    
    self.state = LBStatisticsTaskStateSending;
    
    if (self.type == LBStatisticsTaskTypeDefault)
    {
        NSString *URLStr =[self.url stringByAppendingString:self.params?:@""];
        
        __weak __typeof(&*self) weakSelf = self;
        self.sessionTask = [[AFHTTPSessionManager manager] GET:[URLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //打点返回空串
            [weakSelf requestSuccessedWithResponseString:@""];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            LBSLog(@"error====%@",error);
            [weakSelf requestFailedWithError:error];
        }];
    }
    else if (self.type == LBStatisticsTaskTypeAd){
        
        NSData* loc_jsonData = [self.params dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableData *postData = [NSMutableData dataWithData:loc_jsonData];
        id jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableLeaves error:nil];

        __weak __typeof(&*self) weakSelf = self;
        self.sessionTask = [[AFHTTPSessionManager manager] POST:[self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                                                     parameters:jsonData
                                                       progress:nil
                                                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                            if ([responseObject isKindOfClass:[NSData class]]) {
                                                                NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                                                                [weakSelf requestSuccessedWithResponseString:responseString];
                                                            }
                                                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                            LBSLog(@"error====%@",error);
                                                            [weakSelf requestFailedWithError:error];
                                                        }];
    }
    
    self.retryCount ++;
}



//重新发送
- (void)resend{
    if (self.state == LBStatisticsTaskStateReSendWaiting) {
        self.state = LBStatisticsTaskStateWaiting;
        if ([self.delegate respondsToSelector:@selector(taskWillResend:)])
        {
            [self.delegate taskWillResend:self];
        }
    }
}

#pragma mark - requestSuccessed
- (void)requestSuccessedWithResponseString:(id)responseString{
    if (self.type == LBStatisticsTaskTypeAd)
    {
        if ([responseString isEqualToString:@"true"]) {
            self.state = LBStatisticsTaskStateSuccess;
            if ([self.delegate respondsToSelector:@selector(taskSuccess:)])
            {
                [self.delegate taskSuccess:self];
            }
        } else {
            if  ([self.delegate respondsToSelector:@selector(taskFailOne:error:)]){
                [self.delegate taskFailOne:self error:responseString];
            }
            [self retryDo];
        }
    }
    else if (self.type == LBStatisticsTaskTypeDefault){
        LBSLog(@"strReceive:%@",responseString);
        
        self.state = LBStatisticsTaskStateSuccess;
        if ([self.delegate respondsToSelector:@selector(taskSuccess:)]) {
            [self.delegate taskSuccess:self];
        }
    }
    
}

- (void)requestFailedWithError:(NSError *)error{
    if (self.type == LBStatisticsTaskTypeAd) {
        
        LBSLog(@"%@",error);
        
        if  ([self.delegate respondsToSelector:@selector(taskFailOne:error:)]){
            [self.delegate taskFailOne:self error:error.localizedDescription];
        }
        [self retryDo];
    }
    else if (self.type == LBStatisticsTaskTypeDefault){
        
        LBSLog(@"%@",error);
        
        if ([self.delegate respondsToSelector:@selector(taskFailOne:error:)]) {
            [self.delegate taskFailOne:self error:error.localizedDescription];
        }
        [self retryDo];
    }
}

@end
